package com.example.tagsdemo.directive;

import com.example.tagsdemo.entity.Student;
import com.example.tagsdemo.service.StudentService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class StudentListDirective implements TemplateDirectiveModel {

    @Autowired
    private StudentService studentService;

    private static final String NAME = "name";
    private static final String PAGE_NUMBER = "pageNumber";
    private static final String PAGE_SIZE = "pageSize";
    private static final String SORT = "sort";
    /**
     *
     * @param environment 运行的环境
     * @param map 方法参数map  方法名和值
     * @param templateModels
     * @param templateDirectiveBody 输出形式
     * @throws TemplateException
     * @throws IOException
     */
    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        String name = "";
        Integer pageNumber = 1;
        Integer pageSize = 5;

        if (map.containsKey(NAME)){
            name = String.valueOf(map.get(NAME).toString());
        }
        if (map.containsKey(PAGE_NUMBER)){
            pageNumber = Integer.valueOf(map.get(PAGE_NUMBER).toString());
        }

        if (map.containsKey(PAGE_SIZE)){
            pageSize = Integer.valueOf(map.get(PAGE_SIZE).toString());
        }

        Page<Student> page = studentService.findByName(name, pageNumber, pageSize);

        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        environment.setVariable("page", builder.build().wrap(page));
        templateDirectiveBody.render(environment.getOut());
    }
}
